package com.heima.wemedia.service.impl;

import com.heima.apis.schedule.ITaskClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutcoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private ITaskClient taskClient;


    @Autowired
    private WmNewsAutcoScanService wmNewsAutcoScanService;

    /**
     * 发布延迟任务
     *
     * @param wmNews
     */
    @Override
    public void saveTask(WmNews wmNews) {

        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());  //设置发布日期
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());  //设置任务的类型
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority()); //设置任务的优先级

        WmNews wm = new WmNews();
        wm.setId(wmNews.getId());

        //将对象转换成字节数组
        //方式一：ObjectOutputStream
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        ObjectOutputStream oos = new ObjectOutputStream(bos);
//        oos.writeObject(wm);
//        byte[] byteArray = bos.toByteArray();

        //方式二：借助谷哥的工具类来完成
        byte[] serialize = ProtostuffUtil.serialize(wm);

        task.setParameters(serialize);


        //发起feign远程调用，添加延迟任务
        taskClient.addTask(task);
    }


    /**
     * 定时拉取已经到期的任务
     */
    @Scheduled(fixedDelay = 1000)
    public void pollTask(){

       Task task= taskClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(task!=null){

            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            log.info("开始拉取任务，对id为{}的文章进行审核",wmNews.getId());

            //开始文章审核
            wmNewsAutcoScanService.autoScan(wmNews.getId());
        }
    }
}
